import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addNodeList,
  delNodeList,
  editNodeList,
  getMenuList,
} from "../../api/system/menuManagement";
import { checkData, checkNum } from "../../utils";
export default function menuManagement() {
  //新增操作信息对话框显示与隐藏
  const addOptionDialogVisible = ref(false);
  //操作信息新增数据
  const addOptionForm = reactive({});
  //移除上传图片操作
  function handleRemove(fileList) {
    addFileList.value = fileList;
  }
  //图片上传成功操作
  function handleSuccess(file) {
    addForm.icon = file.data.url;
  }
  //添加菜单图片列表
  const addFileList = ref([]);
  //提交新增操作信息方法
  function submitOption() {
    addNodeList({
      parentId: parentId.value,
      sort: sort.value,
      icon: addOptionForm.icon,
      name: addOptionForm.name,
      url: addOptionForm.url,
      permission: addOptionForm.permission,
      type: 2,
    }).then(() => {
      addOptionDialogVisible.value = false;
      getMenuData();
      ElMessage({
        message: "操作成功",
        type: "success",
      });
    });
  }

  //新增操作信息方法
  function addOptionMenu(data) {
    addOptionDialogVisible.value = true;
    parentId.value = data.id;
    sort.value = data.children.length + 1;
  }

  //复选框选中时ID
  const checkId = ref("");
  const treeRef = ref(null);
  //菜单树形数据
  const treeData = ref([
    {
      name: "菜单信息",
      id: 0,
      type: 0,
      children: [],
    },
  ]);
  //操作树形数据
  const sort = ref(Number);
  const optionData = ref([]);
  //新增表单数据
  const addForm = reactive({});
  //父节点ID
  const parentId = ref(Number);
  //当前复选框Id
  const checkedId = ref("");
  //新增父级对话框显示与隐藏
  const addDialogVisible = ref(false);
  const addChildDialogVisible = ref(false);
  const labelName = ref("");
  //编辑对话框显示与隐藏
  const editDialogVisible = ref(false);
  //编辑节点数据
  const editForm = reactive({});
  //当前ID
  const nodeId = ref(Number);
  //获取图片url
  function getImgUrl(url) {
    addForm.icon = url;
  }
  // 新增表单验证
  const addRules = ref({
    name: [
      { required: true, message: "请输入名称", trigger: "blur" },
      { min: 2, max: 10, message: "长度在 2 到 10 个汉字", trigger: "blur" },
    ],
    url: [
      { required: true, message: "请输入路由地址", trigger: "blur" },
      { validator: checkData },
    ],
    permission: [
      { required: true, message: "请输入授权码", trigger: "blur" },
      { validator: checkData },
    ],
    sort: [
      { required: true, message: "请输入排序数", trigger: "blur" },
      { validator: checkNum },
    ],
  });
  //提交新增菜单操作
  const form = ref(null);
  function submit() {
    form.value.validate((valid) => {
      if (valid) {
        labelName.value = addForm.name;
        addNodeList({
          icon: addForm.icon,
          name: addForm.name,
          parentId: parentId.value,
          url: addForm.url,
          sort: addForm.sort,
          permission: addForm.permission,
          type: 0,
        }).then(() => {
          ElMessage.success("新增菜单成功");
          addDialogVisible.value = false;
          form.value.resetFields();
          addFileList.value = [];
          getMenuData();
        });
      }
    });
  }
  //取消新增父级节点
  function addCancel() {
    addFileList.value = [];
    addDialogVisible.value = false;
    form.value.resetFields();
  }
  //添加菜单
  function add(data) {
    parentId.value = data.id;
    sort.value = data.children.length + 1;
    addForm.parentName = data.name;
    addDialogVisible.value = true;
  }
  //设置tree 复选框只能单选
  function handleNodeClick(data, checked) {
    if (checked === true) {
      checkedId.value = data.id;
      treeRef.value.setCheckedKeys([data.id]);
      optionData.value = [];
    } else {
      if (checkedId.value === data.id) {
        treeRef.value.setCheckedKeys([data.id]);
      }
    }
  }
  //通过子节点获取菜单数据
  function getMenuData() {
    getMenuList().then((res) => {
      //  拆分数组
      treeData.value[0].children = res.data;
    });
  }

  //复选框节点选中操作
  function checkChange(node) {
    //  选中时将当前数据赋值给操作数组
    checkId.value = node.id;
    optionData.value.push(node);
  }
  //删除节点操作
  function remove(node, data) {
    ElMessageBox.confirm("你确定要删除当前节点么?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        if (node.children !== "") {
          //判断当前节点是否有子节点
          delNodeList(data.id)
            .then(() => {
              const parent = node.parent;
              const children = parent.data.children || parent.data;
              const index = children.findIndex((d) => d.id === data.id);
              children.splice(index, 1);
            })
            .catch((error) => {
              console.log(error);
            });
        }
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消操作",
        });
      });
  }
  const editFileList = ref([]);
  const editFormRef = ref(null);
  //编辑节点操作
  function edit(data) {
    editDialogVisible.value = true;
    editForm.name = data.name;
    editForm.url = data.url;
    editForm.icon = data.icon;
    editForm.sort = data.sort;
    editForm.permission = data.permission;
    nodeId.value = data.id;
    editFileList.value.push({ url: data.icon });
  }
  //提交编辑节点操作
  function editSubmit() {
    editFormRef.value.validate((valid) => {
      if (valid) {
        editNodeList(
          {
            name: editForm.name,
            url: editForm.url,
            icon: editForm.url,
            permission: editForm.permission,
            type: 0,
            sort: editForm.sort,
          },
          nodeId.value
        ).then(() => {
          ElMessage.success("修改成功");
          editFormRef.value.resetFields();
          editFileList.value = [];
          editDialogVisible.value = false;
          getMenuData();
        });
      }
    });
  }
  //子节点取消操作
  function editCancel() {
    editFormRef.value.resetFields();
    editFileList.value = [];
    editDialogVisible.value = false;
  }
  function checkFileType(file) {
    const fileName = file.name;
    const fileType = fileName.substring(fileName.lastIndexOf("."));
    // jpeg,.png,.jpg,.bmp,.gif
    if (
      fileType === ".jpg" ||
      fileType === ".png" ||
      fileType === ".jpeg" ||
      fileType === ".bmp" ||
      fileType === ".gif"
    ) {
      // 不处理
    } else {
      ElMessage.error("不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型");
      return false;
    }
  }
  function handleOnExceed() {
    ElMessage.warning("只能上传一张图片，请删除图片后重试");
  }
  function editHandleRemove(fileList) {
    editFileList.value = fileList;
  }
  function editHandleSuccess(file) {
    editForm.url = file.data.url;
  }
  onMounted(() => {
    getMenuData();
  });
  return {
    editCancel,
    editHandleSuccess,
    editHandleRemove,
    editFileList,
    editFormRef,
    addCancel,
    addRules,
    form,
    handleOnExceed,
    checkFileType,
    treeData,
    labelName,
    editSubmit,
    optionData,
    addForm,
    addDialogVisible,
    checkedId,
    treeRef,
    addChildDialogVisible,
    addOptionForm,
    editForm,
    editDialogVisible,
    add,
    handleNodeClick,
    addOptionDialogVisible,
    checkChange,
    remove,
    submit,
    edit,
    addOptionMenu,
    submitOption,
    getImgUrl,
    handleRemove,
    handleSuccess,
    addFileList,
  };
}
